package com.orangelife.mobile.washcar.fragment;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.curry.android.http.OrangeErrorHandler;
import com.curry.android.http.VolleyHttpUtil;
import com.curry.android.util.DialogHelper;
import com.curry.orangelife.mobile.R;
import com.markupartist.android.widget.PullToRefreshListView;
import com.orangelife.mobile.common.view.ConfirmDialog;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.main.biz.GoodsRentOrderBiz;
import com.orangelife.mobile.util.ToastHelper;
import com.orangelife.mobile.washcar.adapter.WashCarOrderFirstListViewAdapter;
import com.orangelife.mobile.washcar.biz.WashCarBiz;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * dd洗车列表
 */
public class WashCarOrderFragment extends android.support.v4.app.Fragment {


    @Bind(R.id.lv_my_order)
    PullToRefreshListView lvMyOrder;
    @Bind(R.id.tvNoBill)
    TextView tvNoBill;
    @Bind(R.id.llPropertyBillN)
    RelativeLayout llPropertyBillN;
    private View view;

    private Dialog dialog;
    /**
     * 一页中数据的条数，初始设置为7条
     */
    private int pageSize = Constant.PAGE_SIZE_DEFAULLT;
    /**
     * 初始页，初始化为第一页
     */
    private int pageNo = Constant.PAGE_NO_DEFAULT;

    private String url = "";

    private List<Map<String,Object>> list = new ArrayList<>();
    private List<Map<String, Object>> list2 = new ArrayList<>();

    private WashCarOrderFirstListViewAdapter adapter ;

    private Handler mHandler;

    private String strOrderID;
    /**
     * 分辨是刷新还是加载更多
     */
    private int flags = 1;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_goodsrent_order,
                    null);
            ButterKnife.bind(this,view);
            findView();

        }
        /*
         * 缓存的rootView需要判断是否已经被加过parent，
		 * 如果有parent需要从parent删除，要不然会发生这个view已经有parent的错误。
		 */
        ViewGroup parent = (ViewGroup) view.getParent();
        if (parent != null) {
            parent.removeView(view);
        }
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        flags = 1;
        pageNo = 1;
        getWashCarOrderList(pageSize, pageNo);
    }

    /**
     * 初始化赋值
     */
    private void findView() {
        tvNoBill.setText("您目前没有订单");
        mHandler = new Handler();
        pullListView();
        getDataFromServer();
        setAdapter();
        pageNo = 1;
        getWashCarOrderList(pageSize, pageNo);
        lvMyOrder.setOnItemLongClickListener(longListener);

    }

    private void setAdapter() {
        adapter = new WashCarOrderFirstListViewAdapter(getActivity(),list2);
        lvMyOrder.setAdapter(adapter);
    }

    /**
     * 下拉刷新的进度条
     */
    private void getDataFromServer() {
        dialog = DialogHelper.getInstance().createLoadingDialog(getActivity(),
                Constant.LOADING);
        dialog.show();
    }

    /**
     * 获取我的dd洗车订单列表
     */
    private void getWashCarOrderList(int pageSize, int pageNo) {
        HashMap<String,String> map = new HashMap<>();
        map.put("pageSize", pageSize + "");
        map.put("pageIndex", pageNo + "");
        WashCarBiz.getInstance().requestCarOrdersList(map, new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject response, int errCode) {
                DialogHelper.closeDialog(dialog);
                if (OrangeErrorHandler.getInstance().isSuccess(response)) {
                    list2 = GoodsRentOrderBiz.getInstance().handleOrderList(response, errCode);
                    updateListView(list2);
                }
            }
        });
    }

    /**
     * 长按删除
     */
    private AdapterView.OnItemLongClickListener longListener = new AdapterView.OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view,
                                       int position, long id) {
            strOrderID = list.get(position - 1).get("orderID").toString();
            isDeleteDialog();
            return true;
        }
    };

    /**
     * 弹出对话框
     */
    private void isDeleteDialog() {
        final ConfirmDialog dialog = new ConfirmDialog(getActivity(), "温馨提示","是否删除?", "否", "是");
        dialog.setClicklistener(new ConfirmDialog.ClickListenerInterface() {
            @Override
            public void doLeft() {
                dialog.dismiss();
            }

            @Override
            public void doRight() {
                getDataFromServer();
                deleteGoodsOrder(strOrderID);
                dialog.dismiss();
            }
        });
        dialog.show();
    }
    private void isDeleteDialog1() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage("是否删除？");
        builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                getDataFromServer();
                deleteGoodsOrder(strOrderID);
                dialog.dismiss();
            }
        });
        builder.setNegativeButton("否", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    /**
     * 删除订单
     */
    private void deleteGoodsOrder(String strOrderID) {
        url = Constant.URL_GOODRENT_ORDER_DELETE;
        HashMap<String, String> map = new HashMap<>();
        map.put("{orderID}",strOrderID);
        GoodsRentOrderBiz.getInstance().requestDelete(map, new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject response, int errCode) {
                DialogHelper.closeDialog(dialog);
                if(OrangeErrorHandler.getInstance().isSuccess(errCode)){
                    ToastHelper.getInstance()._toast("删除成功！");
                    flags = 1;
                    pageNo = 1;
                    getWashCarOrderList(pageSize, pageNo);
                }
            }
        },url);
    }

    /**
     * 下拉刷新列表
     */
    private void pullListView() {
        lvMyOrder.setXListViewListener(new PullToRefreshListView.IXListViewListener() {
            @Override
            public void onRefresh() {
                mHandler.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        // list.clear();
                        flags = 1;
                        pageNo = 1;
                        getWashCarOrderList(pageSize, pageNo);
                        onLoad();
                        adapter.setList(list);
                        adapter.notifyDataSetChanged();
                    }
                }, 2000);
            }

            @Override
            public void onLoadMore() {
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        flags = 0;
                        pageNo += 1;
                        getWashCarOrderList(pageSize, pageNo);
                        onLoad();
                        if (list != null) {
                            adapter.setList(list);
                            adapter.notifyDataSetChanged();
                        }
                    }
                }, 2000);
            }
        });
    }

    @SuppressWarnings("deprecation")
    private void onLoad() {
        lvMyOrder.stopRefresh();
        lvMyOrder.stopLoadMore();
        lvMyOrder.setRefreshTime(new Date().toLocaleString());
    }

    /**
     * 刷新 拉下列表
     *
     * @param list2
     */
    private void updateListView(List<Map<String, Object>> list2) {

        boolean havebill = false;
        if (list2 != null && list != null) {
            if (list2.size() == 0) {
                if (flags == 1) {
                    list.clear();
                    lvMyOrder.setPullLoadEnable(false);
                    adapter.setList(list);
                    adapter.notifyDataSetChanged();
                    havebill = false;
                } else {
                    lvMyOrder.setPullLoadEnable(false);
                    adapter.setList(list);
                    adapter.notifyDataSetChanged();
                    havebill = true;
                }
            } else {
                if (flags == 1) {
                    list.clear();
                    lvMyOrder.setPullLoadEnable(true);
                    list.addAll(list2);
                    adapter.setList(list);
                    adapter.notifyDataSetChanged();
                    havebill = true;
                } else {
                    lvMyOrder.setPullLoadEnable(true);
                    list.addAll(list2);
                    adapter.setList(list);
                    adapter.notifyDataSetChanged();
                    havebill = true;
                }
            }
        } else {
            lvMyOrder.setPullLoadEnable(false);
            havebill=false;
        }
        isNoBill(havebill);
    }

    /**
     * 判断是否有订单显示无订单页面
     *
     * @param havebill
     */
    private void isNoBill(boolean havebill) {
        if (havebill) {
            lvMyOrder.setVisibility(View.VISIBLE);
            llPropertyBillN.setVisibility(View.GONE);
        } else {
            lvMyOrder.setVisibility(View.GONE);
            llPropertyBillN.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}
